#!/bin/bash

echo "=== 修复后台服务启动问题 ==="
echo ""

# 清理可能存在的残留文件
echo "1. 清理残留文件..."
rm -f /tmp/ai_glass_*
pkill -f "ai_glass_test.*daemon" 2>/dev/null
sleep 1

# 重新编译
echo "2. 重新编译程序..."
./build.sh
if [ $? -ne 0 ]; then
    echo "❌ 编译失败"
    exit 1
fi

echo ""
echo "3. 启动后台服务..."

# 启动服务
./build/ai_glass_test --daemon
sleep 3

echo ""
echo "4. 检查服务状态..."

# 使用客户端检查状态
if ./build/ai_glass_cmd --status; then
    echo ""
    echo "✅ 服务启动成功！开始演示..."
    echo ""
    
    echo "5. 演示: 可以正常使用Linux命令"
    echo "执行 'pwd' 命令:"
    pwd
    echo ""
    echo "执行 'whoami' 命令:"
    whoami
    echo ""
    echo "执行 'ls build/' 命令:"
    ls build/
    echo ""
    
    echo "6. 演示: 发送AI Glass命令"
    echo "发送拍照命令..."
    ./build/ai_glass_cmd "AT+AIGLASSPHOTO"
    echo ""
    echo "发送录像命令..."
    ./build/ai_glass_cmd "AT+AIGLASSRECORD 5"
    echo ""
    echo "查询系统状态..."
    ./build/ai_glass_cmd "AT+STATUS"
    echo ""
    
    echo "7. 停止后台服务..."
    ./build/ai_glass_cmd "AT+EXIT"
    sleep 2
    
    echo ""
    echo "🎉 演示完成！"
    echo ""
    echo "✅ 新架构完美解决了问题："
    echo "   - 后台服务不会接管终端"
    echo "   - 可以同时使用Linux命令"
    echo "   - AI Glass功能正常工作"
    echo ""
    echo "📚 使用方法："
    echo "   启动服务: ./build/ai_glass_test --daemon"
    echo "   发送命令: ./build/ai_glass_cmd \"AT+AIGLASSPHOTO\""
    echo "   检查状态: ./build/ai_glass_cmd --status"
    echo "   停止服务: ./build/ai_glass_cmd \"AT+EXIT\""
    
else
    echo ""
    echo "❌ 服务启动失败"
    echo ""
    echo "🔍 故障排除："
    echo "1. 检查日志:"
    echo "   tail -10 /tmp/ai_glass_daemon.log"
    echo ""
    echo "2. 检查进程:"
    echo "   ps aux | grep ai_glass"
    echo ""
    echo "3. 检查文件权限:"
    echo "   ls -la /tmp/ai_glass_*"
    echo ""
    echo "4. 手动清理:"
    echo "   rm -f /tmp/ai_glass_*"
    echo "   pkill -f ai_glass"
    echo ""
    
    # 尝试显示日志
    if [ -f "/tmp/ai_glass_daemon.log" ]; then
        echo "📋 最近的日志信息:"
        tail -10 /tmp/ai_glass_daemon.log
    fi
    
    exit 1
fi